package com.tuling.JUC;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Type JUCLockUtil.java
 * @Desc 生产者消费者
 * @Author wzw
 * @Date 2024/9/10 10:54
 */

//使用if wait 后会出现虚假唤醒的问题
//解决方式使用while wait 方式解决
public class JUCLockUtil {

    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"A").start();

        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.decreace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"B").start();

        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"C").start();

        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                data.decreace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }},"D").start();
    }

}
//使用JUC 工具
class Data2{
    private  int num = 0;
    final Lock lock = new ReentrantLock();
    //同步监听器
    final Condition nullCondition = lock.newCondition();
    public  void increment() throws InterruptedException {
        lock.lock();
        try {
            while (num != 0){
                nullCondition.await();
            }
            num ++;
            System.out.println(Thread.currentThread().getName() +"==>" + num);
            nullCondition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public  void decreace() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0){
                nullCondition.await();
            }
            num --;
            System.out.println(Thread.currentThread().getName() +"==>" + num);
            nullCondition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
